import * as XLSXUtil from "xlsx";
import FileSaver from 'file-saver'

export function importExcel(file) {

    return new Promise(function (resolve){
        const fileReader = new FileReader();
        let resultList = [];

        fileReader.onload = ev => {
            try {
                const data = ev.target.result;
                const workbook = XLSXUtil.read(data, { type: "binary" });
                // 取对应表生成json表格内容
                let sheet = workbook.Sheets['Sheet1'];
                resultList = XLSXUtil.utils.sheet_to_json(sheet);
            } catch (e) {
                console.log("error:" + e);
                return false;
            }
        };
        fileReader.readAsBinaryString(file);
        fileReader.onloadend = () =>  {
            resolve(resultList)
        }
    })
}

/*
    https://blog.csdn.net/liming1016/article/details/122911053
 */
export function exportExcel(name, logListData){
    let wopts = {
        bookType: 'xlsx',
        bookSST: true,
        type: 'binary'
    };
    let workBook = {
        SheetNames: ['Sheet1'],
        Sheets: {},
        Props: {}
    };

    //1、XLSX.utils.json_to_sheet(data) 接收一个对象数组并返回一个基于对象关键字自动生成的“标题”的工作表，默认的列顺序由使用Object.keys的字段的第一次出现确定
    //2、将数据放入对象workBook的Sheets中等待输出
    workBook.Sheets['Sheet1'] = XLSXUtil.utils.json_to_sheet(logListData);

    //3、XLSX.write() 开始编写Excel表格
    //4、changeData() 将数据处理成需要输出的格式
    FileSaver.saveAs(new Blob([changeData(XLSXUtil.write(workBook, wopts))], {type: 'application/octet-stream'}), name)
}

function changeData(s)
{

    //如果存在ArrayBuffer对象(es6) 最好采用该对象
    if (typeof ArrayBuffer !== 'undefined') {

        //1、创建一个字节长度为s.length的内存区域
        let buf = new ArrayBuffer(s.length);

        //2、创建一个指向buf的Unit8视图，开始于字节0，直到缓冲区的末尾
        let view = new Uint8Array(buf);

        //3、返回指定位置的字符的Unicode编码
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;

    } else {
        let buf = new Array(s.length);
        for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
}